/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.AbstractDynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.convert.Converter;
import com.alibaba.csp.sentinel.dashboard.rule.util.ConfigIdUtil;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;

import java.util.List;

/**
 * @author: shaozeming
 * @date: 2022/8/8 15:24
 * @description:
 **/
public class FlowRuleNacosPublisher extends AbstractDynamicRulePublisher {

    private final ConfigService configService;
    private final NacosConfig nacosConfig;

    public FlowRuleNacosPublisher(ConfigService configService,NacosConfig nacosConfig){
        this.configService =configService;
        this.nacosConfig =nacosConfig;
    }


    @Override
    protected void publishPrivate(String app, List<RuleEntity> rules, Class<?> clz) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }

        configService.publishConfig(app + ConfigIdUtil.getKey(clz),
                nacosConfig.getGroupId(), Converter.encode(rules));
    }

    @Override
    protected void publishDefault(String app, List<RuleEntity> rules, Class<?> clz) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        String defaultKey = ConfigIdUtil.getDefaultKey(clz);
        if(defaultKey ==null ||defaultKey.length() ==0){
            return;
        }

        configService.publishConfig(app + ConfigIdUtil.getDefaultKey(clz),
                nacosConfig.getGroupId(), Converter.encode(rules));
    }

}
